<?php


namespace App\Controller\Cooperative;

use App\Annotation\OperationLog;
use \App\Controller\AbstractController;
use App\Request\Cooperative\BindWxMpRequest;
use App\Request\Cooperative\RegisterRequest;
use App\Request\Cooperative\WxUloadRequest;
use App\Service\Cooperative\CooperativeService;

use App\Utils\Upload\Server;

use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;
use function Swlib\Http\build_query;


class CooperativeController extends AbstractController
{
    /**
     * @Inject()
     * @var CooperativeService
     */
    protected $cooperativeService;

    /**
     * @param RegisterRequest $request
     * @return mixed|ResponseInterface
     * @throws \Exception
     */
    public function register(RegisterRequest $request)
    {
        $validated = $request->validated();
        $info = $this->cooperativeService->register($validated['phone'], $validated['code']??'');
        return $this->response->success($info);
    }

    /**
     * @OperationLog(event="获取小程序授权二维码链接",platform="cooperative")
     * @return ResponseInterface
     */
    public function preAuthUrl(){
        $url = $this->cooperativeService->preAuthUrl();
        return $this->response->success($url);
    }

    /**
     * @param int $cooperativeId
     * @return mixed|ResponseInterface
     * @throws \Exception
     */
    public function bindWxMp(int $cooperativeId){
        $status = $this->cooperativeService->bindWxMp($cooperativeId,$this->request->input('auth_code'));
        $url = env("PC_BASE_URL") . '#/BingWxStatus' . '?' . http_build_query([
            'status' => $status
        ]);
        return $this->response->redirect($url);
    }

    /**
     * @OperationLog(event="绑定微信商户号信息",platform="cooperative")
     * @param BindWxMpRequest $request
     * @return mixed|ResponseInterface
     */
    public function bindWxMerchant(BindWxMpRequest $request){
        $validated = $request->validated();
        $this->cooperativeService->bindWxMerchant($validated);
        return $this->response->success();
    }

    /**
     * 上传API证书
     * @param WxUloadRequest $request
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function uploadApi(WxUloadRequest $request)
    {
       $validated = $request->validated();
       $data = $this->cooperativeService->uploadApi($validated);
       return $this->response->success($data);
    }


    /**
     * APi证书下载
     * @OperationLog(event="APi证书下载",platform="cooperative")
     * @param string $id
     * @return mixed
     */
    public function downloadApi(string $id)
    {
       return di(Server::class)->view($id)->downloadFile();
    }


    /**
     * 获取合作商信息
     * @return mixed|ResponseInterface
     */
    public function cooperativeInfo()
    {
        $data = $this->cooperativeService->cooperativeInfo();
        return $this->response->success($data);
    }
}